{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "99c2a3aa",
   "metadata": {},
   "source": [
    "# NumPy 生成日期数据\n",
    "\n",
    "NumPy 提供了 `datetime64` 和 `timedelta64` 数据类型来高效处理日期和时间数据。\n",
    "\n",
    "主要内容：\n",
    "1. `np.datetime64` - 创建单个日期/时间对象\n",
    "2. `np.arange()` 配合日期类型 - 生成日期序列\n",
    "3. `np.timedelta64` - 时间间隔操作\n",
    "4. 日期格式和精度\n",
    "5. 实际应用示例\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2deb82d0",
   "metadata": {},
   "source": [
    "## 1. np.datetime64 - 创建单个日期对象\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a1e4bad",
   "metadata": {},
   "source": [
    "**功能：**\n",
    "`np.datetime64` 用于创建单个日期或时间对象，支持多种日期格式和精度。\n",
    "\n",
    "**语法：**\n",
    "```python\n",
    "np.datetime64(date_string, unit='D')\n",
    "```\n",
    "\n",
    "- **date_string**：日期字符串，支持多种格式（如 '2024-01-01', '2024-01-01T12:00:00' 等）\n",
    "- **unit**：日期精度单位（'Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns'）\n",
    "\n",
    "**常用精度单位：**\n",
    "- `'Y'` - 年 (Year)\n",
    "- `'M'` - 月 (Month)\n",
    "- `'W'` - 周 (Week)\n",
    "- `'D'` - 日 (Day)\n",
    "- `'h'` - 小时 (Hour)\n",
    "- `'m'` - 分钟 (Minute)\n",
    "- `'s'` - 秒 (Second)\n",
    "- `'ms'` - 毫秒 (Millisecond)\n",
    "- `'us'` - 微秒 (Microsecond)\n",
    "- `'ns'` - 纳秒 (Nanosecond)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f261abe7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# 1. 创建日期对象（默认精度为天）\n",
    "date1 = np.datetime64('2024-01-01')\n",
    "print(\"日期（天精度）:\", date1)\n",
    "print(\"数据类型:\", date1.dtype)\n",
    "\n",
    "# 2. 指定不同的精度\n",
    "date2 = np.datetime64('2024-01', 'M')  # 月份精度\n",
    "print(\"\\n日期（月精度）:\", date2)\n",
    "\n",
    "date3 = np.datetime64('2024', 'Y')  # 年份精度\n",
    "print(\"日期（年精度）:\", date3)\n",
    "\n",
    "# 3. 包含时间的日期\n",
    "datetime1 = np.datetime64('2024-01-01T12:30:00')\n",
    "print(\"\\n日期时间:\", datetime1)\n",
    "\n",
    "datetime2 = np.datetime64('2024-01-01T12:30:00.500', 'ms')  # 毫秒精度\n",
    "print(\"日期时间（毫秒精度）:\", datetime2)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9cd2d891",
   "metadata": {},
   "source": [
    "## 2. np.arange() 配合日期类型 - 生成日期序列\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "596ca917",
   "metadata": {},
   "source": [
    "**功能：**\n",
    "使用 `np.arange()` 配合日期对象可以生成日期序列，这是生成连续日期最常用的方法。\n",
    "\n",
    "**语法：**\n",
    "```python\n",
    "np.arange(start_date, stop_date, step, dtype='datetime64')\n",
    "```\n",
    "\n",
    "- **start_date**：起始日期（datetime64 对象或字符串）\n",
    "- **stop_date**：结束日期（不包括在结果中）\n",
    "- **step**：步长（timedelta64 对象或字符串，如 'D' 表示天）\n",
    "- **dtype**：数据类型，通常自动推断为 datetime64\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91fac9bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# 1. 生成日期范围（按天）\n",
    "dates = np.arange('2024-01-01', '2024-01-11', dtype='datetime64[D]')\n",
    "print(\"生成10天的日期序列:\")\n",
    "print(dates)\n",
    "\n",
    "# 2. 使用步长参数\n",
    "dates_weekly = np.arange('2024-01-01', '2024-02-01', 7, dtype='datetime64[D]')\n",
    "print(\"\\n生成每周的日期（步长为7天）:\")\n",
    "print(dates_weekly)\n",
    "\n",
    "# 3. 使用字符串指定步长\n",
    "dates_daily = np.arange(np.datetime64('2024-01-01'), \n",
    "                        np.datetime64('2024-01-11'), \n",
    "                        np.timedelta64(1, 'D'))\n",
    "print(\"\\n使用 timedelta64 指定步长:\")\n",
    "print(dates_daily)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99d5ede1",
   "metadata": {},
   "source": [
    "## 3. np.timedelta64 - 时间间隔操作\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e3a2e30",
   "metadata": {},
   "source": [
    "**功能：**\n",
    "`np.timedelta64` 用于表示时间间隔，可以与日期对象进行加减运算。\n",
    "\n",
    "**语法：**\n",
    "```python\n",
    "np.timedelta64(value, unit='D')\n",
    "```\n",
    "\n",
    "- **value**：时间间隔的数值\n",
    "- **unit**：时间单位（'Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns'）\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2b85057",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# 1. 创建时间间隔\n",
    "delta1 = np.timedelta64(7, 'D')  # 7天\n",
    "delta2 = np.timedelta64(1, 'h')  # 1小时\n",
    "delta3 = np.timedelta64(30, 'm')  # 30分钟\n",
    "\n",
    "print(\"7天间隔:\", delta1)\n",
    "print(\"1小时间隔:\", delta2)\n",
    "print(\"30分钟间隔:\", delta3)\n",
    "\n",
    "# 2. 日期加减运算\n",
    "start_date = np.datetime64('2024-01-01')\n",
    "future_date = start_date + np.timedelta64(10, 'D')  # 10天后\n",
    "past_date = start_date - np.timedelta64(5, 'D')  # 5天前\n",
    "\n",
    "print(f\"\\n起始日期: {start_date}\")\n",
    "print(f\"10天后: {future_date}\")\n",
    "print(f\"5天前: {past_date}\")\n",
    "\n",
    "# 3. 计算日期差\n",
    "date1 = np.datetime64('2024-01-01')\n",
    "date2 = np.datetime64('2024-01-15')\n",
    "diff = date2 - date1\n",
    "print(f\"\\n日期差: {diff} 天\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35fe00ab",
   "metadata": {},
   "source": [
    "## 4. 常用日期序列生成示例\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "314f58df",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# 1. 生成一个月的日期（每天）\n",
    "month_dates = np.arange('2024-01-01', '2024-02-01', dtype='datetime64[D]')\n",
    "print(\"2024年1月的所有日期:\")\n",
    "print(month_dates)\n",
    "print(f\"共 {len(month_dates)} 天\")\n",
    "\n",
    "# 2. 生成工作日（周一到周五，假设按每5天一个周期）\n",
    "# 注意：这只是一个简单示例，实际需要过滤周末\n",
    "work_dates = np.arange('2024-01-01', '2024-01-31', dtype='datetime64[D]')\n",
    "print(\"\\n1月份的日期序列:\")\n",
    "print(work_dates)\n",
    "\n",
    "# 3. 生成按小时的时间序列\n",
    "hourly = np.arange('2024-01-01T00:00', '2024-01-02T00:00', \n",
    "                   dtype='datetime64[h]')\n",
    "print(\"\\n24小时的时间序列（每小时）:\")\n",
    "print(hourly)\n",
    "\n",
    "# 4. 生成按分钟的时间序列（1小时）\n",
    "minutely = np.arange('2024-01-01T00:00', '2024-01-01T01:00', \n",
    "                     dtype='datetime64[m]')\n",
    "print(\"\\n1小时的时间序列（每分钟）:\")\n",
    "print(minutely)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5569fa4a",
   "metadata": {},
   "source": [
    "## 5. 日期数组的常用操作\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9801ed8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# 创建日期数组\n",
    "dates = np.arange('2024-01-01', '2024-01-11', dtype='datetime64[D]')\n",
    "print(\"原始日期数组:\")\n",
    "print(dates)\n",
    "\n",
    "# 1. 日期数组批量加减\n",
    "dates_plus_week = dates + np.timedelta64(7, 'D')  # 所有日期加7天\n",
    "print(\"\\n所有日期加7天:\")\n",
    "print(dates_plus_week)\n",
    "\n",
    "# 2. 计算日期数组的差值\n",
    "diffs = np.diff(dates)  # 计算相邻日期的差值\n",
    "print(\"\\n相邻日期的差值:\")\n",
    "print(diffs)\n",
    "\n",
    "# 3. 筛选特定范围的日期\n",
    "start = np.datetime64('2024-01-05')\n",
    "end = np.datetime64('2024-01-08')\n",
    "mask = (dates >= start) & (dates < end)\n",
    "filtered_dates = dates[mask]\n",
    "print(\"\\n筛选 2024-01-05 到 2024-01-07 的日期:\")\n",
    "print(filtered_dates)\n",
    "\n",
    "# 4. 提取日期属性（需要转换为字符串或使用 pandas）\n",
    "# NumPy datetime64 本身不直接支持提取年/月/日，但可以用于比较\n",
    "print(\"\\n日期数组中的第一个和最后一个日期:\")\n",
    "print(f\"第一个: {dates[0]}\")\n",
    "print(f\"最后一个: {dates[-1]}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e818ae94",
   "metadata": {},
   "source": [
    "## 6. 实际应用案例：生成时间序列数据\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9f7797f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# 案例1：生成2024年第一季度的日期（每天）\n",
    "q1_dates = np.arange('2024-01-01', '2024-04-01', dtype='datetime64[D]')\n",
    "print(f\"2024年第一季度日期数: {len(q1_dates)} 天\")\n",
    "print(f\"日期范围: {q1_dates[0]} 到 {q1_dates[-1]}\")\n",
    "\n",
    "# 案例2：生成股票交易日（假设每周5个交易日）\n",
    "# 生成1月份的日期，然后可以配合业务逻辑筛选交易日\n",
    "trading_days = np.arange('2024-01-01', '2024-01-31', dtype='datetime64[D]')\n",
    "print(f\"\\n1月份的交易日数（假设）: {len(trading_days)} 天\")\n",
    "\n",
    "# 案例3：生成小时级别的数据（用于监控系统）\n",
    "# 生成一周的小时数据\n",
    "hourly_data = np.arange('2024-01-01T00:00', '2024-01-08T00:00', \n",
    "                        dtype='datetime64[h]')\n",
    "print(f\"\\n一周的小时数: {len(hourly_data)} 小时\")\n",
    "print(f\"前5个小时: {hourly_data[:5]}\")\n",
    "\n",
    "# 案例4：创建日期和数值的对应关系\n",
    "dates = np.arange('2024-01-01', '2024-01-11', dtype='datetime64[D]')\n",
    "values = np.random.randn(len(dates))  # 随机生成对应的数值\n",
    "print(\"\\n日期-数值对应关系示例:\")\n",
    "for i in range(min(5, len(dates))):\n",
    "    print(f\"{dates[i]}: {values[i]:.2f}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ddbc34ac",
   "metadata": {},
   "source": [
    "## 7. 注意事项和最佳实践\n",
    "\n",
    "1. **日期精度选择**：根据需求选择合适的精度（'Y', 'M', 'D', 'h', 'm', 's' 等）\n",
    "2. **性能考虑**：datetime64 比 Python 的 datetime 对象更高效，特别适合数组操作\n",
    "3. **日期格式**：推荐使用 ISO 8601 格式（'YYYY-MM-DD' 或 'YYYY-MM-DDTHH:mm:ss'）\n",
    "4. **范围限制**：datetime64 支持的范围通常是 1677-09-21 到 2262-04-11（纳秒精度）\n",
    "5. **时区处理**：NumPy 的 datetime64 不包含时区信息，如需时区请使用 pandas\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
